# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import api, fields, models, _
import datetime


class FapiaoInputFapiao(models.TransientModel):
    _name = "fp.fapiao.input"
    _description = "Fapiao Input"
    _order = 'date_order desc, id desc'

    invoice_type = fields.Selection(
        selection=[
            # ('vat_fapiao', '增值税发票'),  # 草稿状态时, 增值税发票的类型待定
            ('vat_special', '增值税专用发票'),
            ('vat_general', '增值税普通发票'),
            ('vat_general_e', '增值税电子普通发票'),
            ('vat_special_e', '增值税电子专用发票'),
            # ('40', '货物运输业增值税专用发票'),
            # ('50', '机动车销售统一发票'),
            # ('60', '卷式发票'),
            # ('70', '二手车发票'),
            # ('80', '通行费发票'),
        ], default='vat_general_e')

    name = fields.Char(
        string='Order Number', required=True, copy=False, readonly=True,
        states={'draft': [('readonly', False)]}, index=True,
        default=lambda self: _('New'))

    date_order = fields.Datetime(
        string='Order Date', required=False, readonly=True,
        index=True,
        states={'draft': [('readonly', False)]},
        copy=False, default=fields.Datetime.now,
        help="? 开票时, 需要传入的参数.")

    company_id = fields.Many2one(
        'res.company', 'Company', required=True, index=True,
        default=lambda self: self.env.company)

    user_id = fields.Many2one(
        'res.users', string='User', index=True, default=lambda self: self.env.user)

    note = fields.Text()

    buyer_id = fields.Many2one(
        'fp.partner', string='Customer', readonly=True,
        states={'draft': [('readonly', False)]},
        required=True, index=True)

    saler_id = fields.Many2one(
        'fp.partner', string='Saler', readonly=True,
        states={'draft': [('readonly', False)]},
        required=False, index=True, help="票面信息")

    buyer_name = fields.Char(
        string='Buyer Name', related='buyer_id.fapiao_name', store=True)
    buyer_tin = fields.Char(
        string='Buyer TIN', related='buyer_id.tin', store=True)
    buyer_address = fields.Char(
        string='Buyer Address', related='buyer_id.address', store=True)
    buyer_phone = fields.Char(
        string='Buyer Phone', related='buyer_id.phone', store=True)
    buyer_bank_name = fields.Char(
        string='Buyer Bank Name', related='buyer_id.bank_name', store=True)
    buyer_acc_number = fields.Char(
        string='Buyer Bank Account', related='buyer_id.acc_number', store=True)

    buyer_address_phone = fields.Char(
        string='Buyer Address Phone', related='buyer_id.address_phone', store=True,
        help="进项票时, 如何拆分为地址和电话")
    buyer_bank_account = fields.Char(
        string='Buyer Bank And Account', related='buyer_id.bank_account', store=True,
        help="进项票时, 如何拆分为银行和账号")

    saler_name = fields.Char(
        string='Saler Name', related='saler_id.fapiao_name', store=True)
    saler_tin = fields.Char(
        string='Saler TIN', related='saler_id.tin', store=True)
    saler_address = fields.Char(
        string='Saler Address', related='saler_id.address', store=True)
    saler_phone = fields.Char(
        string='Saler Phone', related='saler_id.phone', store=True)
    saler_bank_name = fields.Char(
        string='Saler Bank Name', related='saler_id.bank_name', store=True)
    saler_acc_number = fields.Char(
        string='Saler Bank Account', related='saler_id.acc_number', store=True)

    saler_address_phone = fields.Char(
        string='Saler Address Phone', related='saler_id.address_phone', store=True)
    saler_bank_account = fields.Char(
        string='Saler Bank And Account', related='saler_id.bank_account', store=True)

    amount_untaxed = fields.Float(
        string='Untaxed Amount', compute='_amount_all', store=True)
    amount_tax = fields.Float(
        string='Tax', compute='_amount_all', store=True)
    amount_total = fields.Float(
        string='Total',  compute='_amount_all', store=True)

    amount_untaxed_discount = fields.Float(
        string='Untaxed Discount Amount', compute='_amount_all', store=True)
    amount_tax_discount = fields.Float(
        string='Tax Discount', compute='_amount_all', store=True)
    amount_discount = fields.Float(
        string='Discount',  compute='_amount_all', store=True)

    line_ids = fields.One2many(
        'fp.sale.order.line', 'order_id', string='Order Lines',
        states={'cancel': [('readonly', True)], 'done': [('readonly', True)]}, copy=True, auto_join=True)

    @api.depends('line_ids.amount_total')
    def _amount_all(self):
        for order in self:
            amount_untaxed = amount_tax = 0.0
            amount_untaxed_discount = amount_tax_discount = 0.0

            for line in order.line_ids:
                amount_untaxed += line.amount_untaxed
                amount_tax += line.amount_tax
                amount_untaxed_discount += line.amount_untaxed_discount
                amount_tax_discount += line.amount_tax_discount

            amount_untaxed = round(amount_untaxed, 2)
            amount_tax = round(amount_tax, 2)
            amount_untaxed_discount = round(amount_untaxed_discount, 2)
            amount_tax_discount = round(amount_tax_discount, 2)

            order.update({
                'amount_untaxed': amount_untaxed,
                'amount_tax': amount_tax,
                'amount_total': round(amount_untaxed + amount_tax, 2),
                'amount_untaxed_discount': amount_untaxed_discount,
                'amount_tax_discount': amount_tax_discount,
                'amount_discount': round(amount_untaxed_discount + amount_tax_discount, 2)
            })


class FapiaoInputFapiaoLine(models.TransientModel):
    _name = 'fp.fapiao.input.line'
    _description = 'Fapiao Input Line'
    _order = 'fapiao_id, sequence, id'

    fapiao_id = fields.Many2one(
        'fp.fapiao', string='Fapiao',
        required=True, ondelete='cascade', index=True, copy=False)

    sequence = fields.Integer(string='Sequence', default=10)

    name = fields.Char(string='Label')

    product_id = fields.Many2one(
        'fp.product', string='Product', required=True, index=True)

    vat_product_id = fields.Many2one(
        string='税收商品ID', related='product_id.vat_product_id', store=True)

    vat_product_code = fields.Char(
        string='Var Product code', related='product_id.vat_product_code', store=True)
    vat_product_name = fields.Char(
        string='Var Product Name', related='product_id.vat_product_name', store=True)
    product_code = fields.Char(
        string='Product code', related='product_id.code', store=True)
    product_name = fields.Char(
        string='Product Name', related='product_id.name', store=True)
    product_spec = fields.Char(
        string='Spec', related='product_id.spec', store=True)
    product_uom = fields.Char(
        string='Uom', related='product_id.uom', store=True)

    tax_ratio = fields.Float(string='tax_ratio', required=True, default=13)
    quantity = fields.Float(string='Quantity', required=True, default=1.0)
    price_unit = fields.Float('Unit Price', required=True, default=1.0)
    amount_total = fields.Float(string='Total')

    amount_untaxed = fields.Float(
        string='Untaxed Amount', compute='_compute_amount', store=True)
    amount_tax = fields.Float(
        string='Tax', compute='_compute_amount', store=True)

    amount_discount = fields.Float(string='Discount Amount',  default=0.0)

    amount_untaxed_discount = fields.Float(
        string='Discount Untaxed Amount', compute='_compute_discount', store=True)
    amount_tax_discount = fields.Float(
        string='Discount Tax', compute='_compute_discount', store=True)

    @api.onchange('tax_ratio')
    def _onchage_for_tax_ratio(self):
        for line in self:
            line._onchage_set_amount()

    @api.onchange('amount_total')
    def _onchage_for_amount_total(self):
        for line in self:
            if not line.amount_total:
                line.amount_total = 1.0
            if not line.quantity:
                line.quantity = 1.0

            total = line.amount_total
            total = round(total, 2)

            line.amount_total = total
            price_unit = total / line.quantity
            price_unit = round(price_unit, 2)
            line.price_unit = price_unit

            line._onchage_set_amount()

    @api.onchange('price_unit')
    def _onchage_for_price_unit(self):
        for line in self:
            if not line.price_unit:
                line.price_unit = 1.0
            if not line.quantity:
                line.quantity = 1.0

            total = line.quantity * line.price_unit
            total = round(total, 2)
            line.amount_total = total
            line._onchage_set_amount()

    @api.onchange('quantity')
    def _onchage_for_quantity(self):
        for line in self:
            if not line.price_unit:
                line.price_unit = 1.0
            if not line.quantity:
                line.quantity = 1.0

            total = line.quantity * line.price_unit
            total = round(total, 2)
            line.amount_total = total

            line._onchage_set_amount()

    def _onchage_set_amount(self):
        amount_total = self.amount_total
        tax_ratio = self.tax_ratio/100
        amount_untaxed = amount_total / (1 + tax_ratio)
        amount_untaxed = round(amount_untaxed, 2)
        amount_tax = amount_total - amount_untaxed
        amount_tax = round(amount_tax, 2)
        self.amount_untaxed = amount_untaxed
        self.amount_tax = amount_tax

    @api.depends('amount_discount')
    def _compute_discount(self):
        for line in self:
            untaxed = line.amount_discount / (1 + (line.tax_ratio/100))
            untaxed = round(untaxed, 2)
            tax = line.amount_discount - untaxed
            tax = round(tax, 2)

            line.amount_untaxed_discount = untaxed
            line.amount_tax_discount = tax

    @api.depends('quantity', 'price_unit')
    def _compute_amount(self):
        for line in self:
            amount_total = line.price_unit * line.quantity
            amount_total = round(amount_total, 2)
            amount_untaxed = amount_total / (1 + (line.tax_ratio/100))
            amount_untaxed = round(amount_untaxed, 2)
            amount_tax = amount_total - amount_untaxed
            amount_tax = round(amount_tax, 2)

            line.amount_total = amount_total
            line.amount_untaxed = amount_untaxed
            line.amount_tax = amount_tax
